package com.smm.web.vmc.filter;

import com.smm.web.vmc.service.UserService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zhenghao on 2016/9/6.
 *
 */
@Slf4j
public class UserLoginFilter implements Filter {



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("--------------in user login filter");

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //检查session中是否有用户信息，如果没有，跳转到登陆页面
        boolean userInSession = checkSessionUser(request);

        log.info("--------------userInSession:"+userInSession);

        if(!userInSession){

            response.sendRedirect(request.getContextPath()+"/login.do");

            return;
        }

        //继续正常访问
        filterChain.doFilter(servletRequest,servletResponse);

    }


    //检查session中是否有用户信息，如果有 返回 true，否则返回false
    private boolean checkSessionUser(HttpServletRequest request) {

        return request.getSession().getAttribute(UserService.USER_SESSION_KEY)!=null;

    }

    @Override
    public void destroy() {

    }
}
